package com.haiqi.modules.film.schedule.film2018;

import com.haiqi.modules.film.mapper.DigDao;
import com.haiqi.modules.film.model.DigEntity;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Selectable;

/**
 * Created by hythzx on 2016/8/12.
 * 获取下载目录
 */
@Component
public class CatalogSchedule implements PageProcessor{

    @Autowired
    private FilmDetailSpider filmDetailSpider;

    @Autowired
    private DigDao digDao;

    Site site = Site.me().setRetryTimes(3).setSleepTime(100);

    private Logger logger = Logger.getLogger(this.getClass());

    @Override
    public void process(Page page) {
        Selectable filmUrls = page.getHtml().xpath("//a/@href").regex(".*/i/.*");  //电影的页面
        Selectable xpath = page.getHtml().xpath("//a/@href").regex(".*/[0-9]/.*");  //目录的页面
        Selectable newFilmCatalog = page.getHtml().xpath("//a/@href").regex(".*/html/.*"); //新版分类，可能为电影，也可能为目录
        for (Selectable selectable : filmUrls.nodes()) {
            filmDetailSpider.run(selectable.get());
        }
        for (String s : xpath.all()) {
            this.digUrl(s);
        }

        for (String s : newFilmCatalog.all()) {
            filmDetailSpider.run(s);
        }

        for (String s : newFilmCatalog.all()) {
            this.digUrl(s);
        }
        logger.info("---------------此次挖掘执行完毕----------------");
    }

    @Override
    public Site getSite() {
        return site;
    }

    @Scheduled(fixedRate=60000000)
    public void run(){
        logger.info("----------------------挖掘程序启动-------------------");
        Spider.create(this).addUrl("http://www.dy2018.com/").thread(5).run();
    }

    /**
     * 对URL惊醒挖掘
     * @param url
     */
    public void digUrl(String url){
        DigEntity digEntity = digDao.selectByPrimaryKey(url);
        if(digEntity != null){
            logger.info("----------------该地址已经挖掘，无需二次操作"+url+"-----------------");
            return;
        }
        digEntity = new DigEntity();
        digEntity.setUrl(url);
        digDao.insertSelective(digEntity);
        logger.info("----------------------对子页面进行挖掘，挖掘的地址是：" + url + "-----------------------------------");
        Spider.create(this).addUrl(url).thread(5).run();
    }

}
